<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">

            <div class="search-item">
                <label>平台名称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.name"
                        clearable
                        placeholder="机构名称"
                    ></el-input>
                </div>
            </div>

            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                style="margin-bottom: 2em"
                icon="el-icon-plus"
                @click="clickAdd('创建平台')"
            >创建平台
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
                default-expand-all
                @selection-change="tableSelectionChange"
            >
                <el-table-column
                    prop="id"
                    label="平台KEY"
                    min-width="40"
                    align="center"
                ></el-table-column>
                <el-table-column
                    prop="name"
                    label="平台名称"
                    min-width="40"
                    align="center"
                ></el-table-column>
                <el-table-column
                    prop="channelBusiness.mobile"
                    label="绑定手机号"
                    min-width="40"
                    align="center"
                >
                </el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    width="450"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            v-if="!scope.row.edit"
                            lass="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="
                                clickSimpleEdit(
                                    scope.row,
                                    '机构信息',
                                    null,
                                    groupDetail
                                )
                            "
                        >编辑
                        </el-button>

                        <el-button
                            v-if="!scope.row.edit"
                            lass="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="groupPermissionSet(scope.row, '平台权限设置')"
                        >考试权限设置
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            type="text"
                            size="mini"
                            class="danger"
                            icon="el-icon-delete"
                            :loading="scope.row.opLoading"
                            @click="
                                tableDelete(
                                    '/user/sys/group/delete',
                                    {
                                        id: scope.row.id
                                    },
                                    true
                                )
                            "
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                background
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
        <el-dialog
            :title="dialogFormTitle"
            :visible.sync="dialogFormVisible"
            :before-close="dialogClose"
            custom-class="two-dialog"
            width="800px !important"
        >
            <el-form
                ref="dataForm"
                :model="dataForm"
                label-width="8em"
                :rules="dataFormRule"
            >
                <div class="row">
                    <el-form-item label="平台名称" prop="name">
                        <el-input v-model="dataForm.name"></el-input>
                    </el-form-item>
                </div>
                <div class="row">
                    <el-form-item label="前台显示名称" prop="alias">
                        <el-input v-model="dataForm.alias"></el-input>
                    </el-form-item>

                </div>
                <div class="row">
                    <el-form-item label="到期时间" prop="expireTime">
                        <el-date-picker
                            v-model="dataForm.expireTime"
                            :picker-options="datePickOption"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择到期时间"
                        >
                        </el-date-picker>
                    </el-form-item>
                </div>

                <el-form-item label="备注" prop="remark">
                    <el-input
                        v-model="dataForm.remark"
                        type="textarea"
                        rows="5"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="header" label="水印" class="header">
                    <el-upload
                        class="avatar-uploader"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false"
                        accept=".jpg,.png,.jpeg"
                        :auto-upload="false"
                        :on-change="headerChange"
                    >
                        <img
                            v-if="base64Header || dataForm.watermark"
                            :src="base64Header || coverImage(dataForm.watermark)"
                            class="avatar"
                        />
                        <i
                            v-else
                            class="el-icon-plus avatar-uploader-icon"
                        ></i>
                    </el-upload>
                </el-form-item>
                <el-divider content-position="left">账号信息</el-divider>
                <el-form-item prop="channelBusiness.mobile" label="手机号">
                    <el-input v-model="dataForm.channelBusiness.mobile"></el-input>
                </el-form-item>
                <el-form-item prop="password" label="密码">
                    <el-input
                        v-model="dataForm.channelBusiness.password"
                        type="password"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="roleIds" label="菜单角色">
                    <el-select
                        v-model="dataForm.channelBusiness.roleIds"
                        v-loading="searchRolesFlag"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入关键词"
                    >
                        <el-option
                            v-for="item in rolesList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="dialogClose"
                >取 消</el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="formDataSave('/user/sys/group/update')"
                >保 存</el-button
                >
            </span>
        </el-dialog>

        <el-dialog
            :title="dialogPermissionTitle"
            :visible.sync="dialogPermissionVisible"
            :before-close="dialogClose"
            custom-class="two-dialog"
        >
            <el-tabs  type="card" >
                <el-tab-pane
                             v-for="(item) in industryData"
                             :key="item.id"
                             :label="getTabCheck(item)"
                             :name="item.id"
                >
                    <el-checkbox  :checked="isIndeterminate[item.id]" :indeterminate="isIndeterminate[item.id]"   @change="(value) => handleCheckAllChange(value,item.id,item.exams)">全选</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="checkedExams" @change="(value) => handleCheckedCitiesChange(value,item.id,item.exams)">
                        <el-checkbox v-for="exam in item.exams"   :key="exam.id"  :label="exam.id" >{{exam.name}}</el-checkbox>
                    </el-checkbox-group>
                </el-tab-pane>
            </el-tabs>
            <span slot="footer" class="dialog-footer">
            <el-button :loading="submitFlag" @click="dialogClose"
            >取 消</el-button
            >
            <el-button
                :loading="submitFlag"
                type="primary"
                @click="setPermission"
            >保 存</el-button
            >
            </span>
        </el-dialog>


    </div>
</template>

<script>
import {TablePage, objSign} from "@/layout/mixin/iVue.js";
import {mapState} from "vuex";
import { examBase } from "@/layout/mixin/examBase";
import {get, put, post} from "@/api/request";
import {isMobile} from "@/utils/validate.js";
import {checkMobileExits, fetchRoleList} from "@/api/user";
import {ossUpload} from "@/utils/file";

export default {
    name: "Group",
    components: {

    },
    mixins: [TablePage,examBase],
    props: {
        groupIpId: {
            type: Number,
            default: null
        }
    },
    data() {
        return {
            queryData: {
                name: null,

            },
            isIndeterminate: {"yiyao":false},
            checkAll: false,
            checkedExams: [],
            dialogPermissionVisible: false,
            dialogPermissionTitle: null,
            checkedInd:[],
            datePickOption: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
                }
            },
            searchRolesFlag:false,
            dataFormRule: {
                name: [
                    {
                        required: true,
                        message: "请输入姓名",
                        trigger: "blur"
                    },
                    {
                        min: 2,
                        max: 10,
                        message: "长度在 2 到 10 个字符",
                        trigger: "blur"
                    }
                ],
                "channelBusiness.mobile": [
                    {
                        required: true,
                        message: "请输入登录手机号",
                        trigger: "blur"
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (!this.addAction) {
                                callback();
                            }
                            if (value) {
                                if (isMobile(value)) {
                                    checkMobileExits({
                                        mobile: value,
                                        userType: "admin"
                                    }).then(res => {
                                        if (res) {
                                            callback(
                                                new Error("手机号已被使用")
                                            );
                                        } else {
                                            callback();
                                        }
                                    });
                                } else {
                                    callback(new Error("请输入正确的手机号"));
                                }
                            }
                        },
                        trigger: "blur"
                    }
                ],
                "channelBusiness.password": [
                    {
                        required: true,
                        message: "请输入密码",
                        trigger: "blur"
                    },
                    {
                        min: 6,
                        max: 20,
                        message: "长度在 6 到 20 个字符",
                        trigger: "blur"
                    }
                ],
                "channelBusiness.roleIds":[
                    {
                        required: true,
                        message: "请选择角色信息",
                        trigger: "blur"
                    },
                ]
            },
            base64Header: null,

        };
    },
    computed: {
        ...mapState({

        })
    },
    watch: {},
    created() {
        this.searchRoles();
    },
    mounted() {
    },
    methods: {
        search(queryData) {
            this.loadTable("/user/sys/group/page", queryData, true);
        },
        searchRoles() {
            this.searchRolesFlag = true;
            fetchRoleList({
                size: 100
            }).then(data => {
                this.rolesList = data;
                this.searchRolesFlag = false;
            });
        },
        groupPermissionSet(row,title){
            this.dialogPermissionVisible = true;
            this.dialogPermissionTitle = title;
            this.groupPermissionGrupId = row.id;
            get("/user/sys/group/getPermissionByGroupId/"+row.id).then(res =>{
                this.checkedExams = res[0].examActionIds;
                this.checkedInd = res[0].industryActionIds;

            })
            this.loadIndustry().then(res =>{
                this.industryData.forEach(item => {
                    this.loadExam(item.id).then(exam=>{
                        this.$set(item, "exams", exam);
                        this.handleCheckedCitiesChange(true,item.id,exam);
                    });
                });
            });
        },
        handleCheckAllChange(val,node,exams) {
            if(val){
                if(this.checkedInd.indexOf(node) === -1){
                    this.checkedInd.push(node);
                }
                exams.forEach(item => {
                    if (this.checkedExams.indexOf(item.id) === -1) {
                        this.checkedExams.push(item.id);
                    }
                });
            }else{
                if(this.checkedInd.indexOf(node) !== -1){
                    this.checkedInd.splice(this.checkedInd.indexOf(node), 1);
                }
                if (this.checkedExams.length > 0){
                    exams.forEach(item => {
                        if (this.checkedExams.indexOf(item.id) !== -1) {
                            this.checkedExams.splice(this.checkedExams.indexOf(item.id), 1);
                        }
                    });
                }
            }
        },
        handleCheckedCitiesChange(value,node,exams) {
            var isCheckAll = true;
            exams.some(item => {
                if (this.checkedExams.indexOf(item.id) === -1) {
                    isCheckAll = false;
                    return true;
                }
            });
            this.$set(this.isIndeterminate,node,isCheckAll);
        },
        setPermission(){
            this.checkedInd = [];
            this.industryData.forEach(item => {
                if(item.exams.length>0){
                    item.exams.forEach(exam=>{
                        if(this.checkedExams.indexOf(exam.id)!==-1 && this.checkedInd.indexOf(item.id) === -1){
                            this.checkedInd.push(item.id)
                        }
                    })
                }
            })
            let data = {
                groupId:this.groupPermissionGrupId,
                examList:this.checkedExams,
                industryList:this.checkedInd,
            }
            post("/user/sys/group/set-permission",data).then(res =>{
                if(res){
                    this.$message.success("设置成功");
                    this.dialogClose();
                }
            })
        }
        ,getTabCheck(item){
            if (this.checkedInd.indexOf(item.id)!==-1){
                return item.name+"[已选]"
            }else{
                return item.name
            }

        },
        headerChange(file, fileList) {
            if (fileList.length > 1) {
                fileList.splice(0, 1);
            }
            const elFile = fileList[0];
            file = fileList[0].raw;
            let imgReaderl = new FileReader();
            imgReaderl.onload = evt => {
                this.base64Header = evt.target.result;
            };
            imgReaderl.readAsDataURL(file);
            ossUpload("cdn", file.name, file, p => {
                elFile.percentage = p * 100;
                elFile.status = "uploading";
            }).then(result => {
                this.dataForm.watermark = result;
                elFile.status = "done";
            });
        }
    }
}
;
</script>

<style lang="scss" scoped>
.step {
    padding: 0.3rem 0;
    background: #f1f1f1;
}

.link-div {
    display: flex;
    justify-content: space-between;
}

.setting-process {
    .setting-p {
        margin: 0.7em 0;
    }

    .cover {
        width: 6em;
        height: 8rem;
        border-radius: 0.4rem;
        border: 1px solid #ececec;
        margin-bottom: 0.2rem;
    }
}

.drawer {
    position: relative;

    .records {
        position: absolute;
        left: 0;
        bottom: 2em;
        width: 100%;

        .p-title {
            margin-bottom: 30px;
        }

        .step {
            overflow: auto;
        }

        .icon-header {
            width: 30px;
            border-radius: 50%;
        }

        .row-til {
            white-space: nowrap;
        }
    }

    .op-box {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        padding: 0.3em 0;
        box-shadow: 0px 0px 14px -8px rgba(0, 0, 0, 0.67);
    }
}
</style>
<style>
.group.i-dialog {
    margin-top: 5vh !important;
    width: fit-content;
}

.header .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.header .avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.header .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 20px;
    line-height: 20px;
    text-align: center;

}

.header .avatar {
    width: 100px;
    height: 20px;
    display: block;
}
.minWidthClear {
    min-width: 2em !important;
}
</style>
